package a66weding.com.jiehuntong.activity;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;

import a66weding.com.jiehuntong.R;
import a66weding.com.jiehuntong.beans.CommonResultBean;
import a66weding.com.jiehuntong.beans.ErrorBean;
import a66weding.com.jiehuntong.beans.GiftBean;
import a66weding.com.jiehuntong.beans.HttpRequestBean;
import a66weding.com.jiehuntong.beans.SuccessBean;
import a66weding.com.jiehuntong.common.MessageEvent;
import a66weding.com.jiehuntong.common.utils.CUtils;
import a66weding.com.jiehuntong.http.HttpHandleUtil;
import a66weding.com.jiehuntong.http.OnNetResultListener;
import a66weding.com.jiehuntong.http.RequestCode;
import a66weding.com.jiehuntong.http.UrlDealUtil;

public class ToolsGiftAddGiftActivity extends Activity implements View.OnClickListener, CompoundButton.OnCheckedChangeListener, OnNetResultListener {
    private Button mGiftCommitBtn;
    private ImageView  mFromphoneIv ;
    private EditText mPersonNameEt ;
    private EditText mMoneyEt ;
    private CheckBox mMenParentChbox ;
    private CheckBox mWomenParentChbox ;
    private CheckBox mNewPeopleChbox ;
    private TextView mBackTv ;
    private LinearLayout mBackLay ;
    private EditText mRemarkEt ;
    private TextView mTitleTv ;
    private static final int PICK_CONTACT=2;
    private static final int PARENTCHECKED=1;
    private static final int WOMENPARENTCHECKED=2;
    private static final int PEOPLECHECKED=3;
    private String mCurrentName;
    private int mCurrentChecked;
    private PopupWindow mCommitpop;
    private boolean isEdit;
    private Intent intent;
    private int cashGiftID;
    private GiftBean.DataBean dataBean;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tools_gift_add_gift);
        intent = this.getIntent();
        if(intent !=null) {
            isEdit = intent.getBooleanExtra("isEdit", false);
        }
        initview();
    }
    private void initview() {
        mGiftCommitBtn = (Button) findViewById(R.id.btn_tools_dayplan_editcommit);
        mFromphoneIv = (ImageView) findViewById(R.id.iv_addgift_fromphone);
        mPersonNameEt = (EditText) findViewById(R.id.et_tools_gift_personname);
        mMoneyEt = (EditText) findViewById(R.id.et_tools_gift_money);
        mMenParentChbox = (CheckBox) findViewById(R.id.rbtn_addgift_menparentguest);
        mWomenParentChbox = (CheckBox) findViewById(R.id.rbtn_addgift_womenparentguest);
        mNewPeopleChbox = (CheckBox) findViewById(R.id.rbtn_addgift_guest);
        mBackTv = (TextView) findViewById(R.id.tv_tools_dayplan_backcontent);
        mBackLay = (LinearLayout) findViewById(R.id.llay_toolsheader_back);
        mRemarkEt = (EditText)findViewById(R.id.et_addgift_remark);
        mTitleTv = (TextView) findViewById(R.id.tv_tools_dayplan_title);

        if(isEdit) {
            mTitleTv.setText("编辑");
            GiftBean.DataBean dataBean=(GiftBean.DataBean) intent.getSerializableExtra("DataBean");
               if(dataBean!=null) {
                   cashGiftID = dataBean.getCashGiftID();
                   String cashGiftName = dataBean.getCashGiftName();
                   double cashGiftAmountD = dataBean.getCashGiftAmount();
                   int cashGiftAmount = (int)cashGiftAmountD;
                   int cashGiftParent = dataBean.getCashGiftParent();
                   String cashGiftRemark = dataBean.getCashGiftRemark();
                   mPersonNameEt.setText(cashGiftName);
                   mPersonNameEt.setSelection(cashGiftName.length());
                   mMoneyEt.setText(String.valueOf(cashGiftAmount));
                   switch (cashGiftParent) {
                           case 1:
                               mMenParentChbox.setChecked(true);
                           break;
                            case 2:
                                mWomenParentChbox.setChecked(true);
                           break;
                            case 3:
                                mNewPeopleChbox.setChecked(true);
                           break;
                   }
                   mRemarkEt.setText(cashGiftRemark);
               }
        }else{
            mTitleTv.setText("礼金记账本");
        }
        mBackTv.setText("礼金");
        mNewPeopleChbox.setOnCheckedChangeListener(this);
        mWomenParentChbox.setOnCheckedChangeListener(this);
        mMenParentChbox.setOnCheckedChangeListener(this);
        mGiftCommitBtn.setOnClickListener(this);
        mFromphoneIv.setOnClickListener(this);
        mBackLay.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
                case R.id.iv_addgift_fromphone:
                    getPhoneContacts2();
                break;
                case R.id.llay_toolsheader_back:
                    finish();
                break;
                 case R.id.btn_tools_dayplan_editcommit:
                    boolean isCorrect= checkContent();
                     if(isCorrect) {
                         String personName = mPersonNameEt.getText().toString().trim();
                         String money = mMoneyEt.getText().toString().trim();
                         boolean checked = mMenParentChbox.isChecked();
                         boolean checked1 = mWomenParentChbox.isChecked();
                         boolean checked2 = mNewPeopleChbox.isChecked();
                         if(checked) {
                             mCurrentChecked=PARENTCHECKED;
                         }else if(checked1){
                             mCurrentChecked=WOMENPARENTCHECKED;
                         }else if(checked2){
                             mCurrentChecked=PEOPLECHECKED;
                         }
                         String remark = mRemarkEt.getText().toString().trim();
                        if(isEdit) {
                            String url= UrlDealUtil.getRealUrl(RequestCode.UPDATE_CASHGIFT);
                            HashMap<String,String> requestParams=new HashMap<String,String>();
                            requestParams.put("CashGiftID",""+cashGiftID);
                            requestParams.put("CashGiftName",personName);
                            requestParams.put("CashGiftAmount",money);
                            requestParams.put("CashGiftParent",""+mCurrentChecked);
                            requestParams.put("CashGiftRemark",remark);
                            dataBean = new GiftBean.DataBean();
                            dataBean.setCashGiftID(cashGiftID);
                            dataBean.setCashGiftName(personName);
                            dataBean.setCashGiftAmount(Integer.valueOf(money));
                            dataBean.setCashGiftParent(mCurrentChecked);
                            dataBean.setCashGiftRemark(remark);
                            HttpRequestBean httpRequestBean = new HttpRequestBean(RequestCode.POSTEQUEST, url,
                                    this, CommonResultBean.class, RequestCode.UPDATE_CASHGIFT, requestParams);
                            HttpHandleUtil.executeCommonPost(this,httpRequestBean);
                        }else{
                            String url= UrlDealUtil.getRealUrl(RequestCode.ADDCASHGIFT);
                             HashMap<String,String> requestParams=new HashMap<String,String>();
                             requestParams.put("CashGiftName",personName);
                             requestParams.put("CashGiftAmount",money);
                             requestParams.put("CashGiftParent",""+mCurrentChecked);
                             requestParams.put("CashGiftRemark",remark);
                             HttpRequestBean httpRequestBean = new HttpRequestBean(RequestCode.POSTEQUEST, url,
                                     this, CommonResultBean.class, RequestCode.ADDCASHGIFT, requestParams);
                             HttpHandleUtil.executeCommonPost(this,httpRequestBean);
                        }
                         showCommitPopupWindow(view);
                     }
                break;
        }

    }

    private boolean checkContent() {
        boolean flag=false;
        String personName = mPersonNameEt.getText().toString().trim();
        if(TextUtils.isEmpty(personName)) {
            CUtils.showToast("宾客姓名不能为空！");
            return flag;
        }
        String money = mMoneyEt.getText().toString().trim();
        if(TextUtils.isEmpty(money)) {
            CUtils.showToast("金额不能为空！");
            return flag;
        }
        flag=true;
        return flag;
    }
    private void getPhoneContacts2(){
        Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
        startActivityForResult(intent, PICK_CONTACT);
    }
    @Override
    public void onActivityResult(int reqCode, int resultCode, Intent data) {
        super.onActivityResult(reqCode, resultCode, data);
        switch (reqCode) {
            case (PICK_CONTACT) :
                if (resultCode == Activity.RESULT_OK) {
                    Uri contactData = data.getData();
                    Cursor c =  managedQuery(contactData, null, null, null, null);
                    if (c.moveToFirst()) {
                        mCurrentName = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                        mPersonNameEt.setText(mCurrentName);
                    }
                }
                break;
        }
    }
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
       switch (buttonView.getId()) {
               case R.id.rbtn_addgift_menparentguest:
                    if(isChecked) {
                        mNewPeopleChbox.setChecked(false);
                        mWomenParentChbox.setChecked(false);
                    }
               break;
               case R.id.rbtn_addgift_womenparentguest:
                    if(isChecked) {
                        mMenParentChbox.setChecked(false);
                        mNewPeopleChbox.setChecked(false);
                    }
               break;
               case R.id.rbtn_addgift_guest:
                    if(isChecked) {
                        mMenParentChbox.setChecked(false);
                        mWomenParentChbox.setChecked(false);
                    }
               break;

       }
    }


    public void showCommitPopupWindow(View view) {
        // 一个自定义的布局，作为显示的内容
        View contentView = LayoutInflater.from(this).inflate(
                R.layout.pop_tools_wedregister_commit, null);
        mCommitpop = new PopupWindow(contentView,
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
        mCommitpop.setTouchable(true);
        contentView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mCommitpop.dismiss();
            }
        });
        mCommitpop.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });
        //设置在屏幕中的显示位置
        mCommitpop.showAtLocation(view, Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL,0,0);
        mCommitpop.showAsDropDown(view);
    }
    @Override
    public void onSucess(SuccessBean sucessbean) {
        MessageEvent messageEvent = new MessageEvent();
        if(dataBean!=null) {
            messageEvent.setGiftData(dataBean);
        }
        EventBus.getDefault().post(messageEvent);
        if(mCommitpop!=null) {
            mCommitpop.dismiss();
        }
        finish();
    }
    @Override
    public void onError(ErrorBean errorBean) {
        if(mCommitpop!=null) {
            mCommitpop.dismiss();
        }
        CUtils.showToast("添加礼金失败，请重试！");
    }
}
